package com.yuanduo_app.utils;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;

import cn.ydxlm.maplib.MapManager;
import com.xujl.fastlib.utils.LogS;
import com.xujl.fastlib.utils.NumberUtils;
import com.xujl.fastlib.utils.StringUtils;

import com.yuanduo_app.MainApplication;
import com.yuanduo_app.consts.BundleKey;
import com.yuanduo_app.ui.common.control.CommonWebActivityControl;
import com.yuanduo_app.window.CommonInfoWindow;

import java.math.BigDecimal;

public class MapUtils {
    public static final int PRIVATE_CODE = 23;

    /**
     * 打开百度地图导航功能(默认坐标点是高德地图，需要转换)
     *
     * @param slat  起点纬度
     * @param slon  起点经度
     * @param sname 起点名称 可不填（0,0，null）
     * @param dlat  终点纬度
     * @param dlon  终点经度
     * @param dname 终点名称 必填
     */
    public static void openBaiDuNavi (double slat, double slon, String sname, double dlat, double dlon, String dname) {
        String uriString = null;
        StringBuilder builder = new StringBuilder("baidumap://map/direction?mode=driving&");
        if (slat != 0) {
            //起点坐标转换
            builder.append("origin=latlng:")
                    .append(slat)
                    .append(",")
                    .append(slon)
                    .append("|name:")
                    .append(sname);
        }
        builder.append("&destination=latlng:")
                .append(dlat)
                .append(",")
                .append(dlon)
                .append("|name:")
                .append(dname);
        uriString = builder.toString();
        final boolean isSuccess = goMap(Uri.parse(uriString), "com.baidu.BaiduMap");
        if (!isSuccess) {
            final CommonInfoWindow infoWindow = new CommonInfoWindow(MainApplication.getApplication(),
                    CommonInfoWindow.createBuilder()
                            .setInfo("当前未安装百度地图，是否去安装？")
                            .setRightStr("确定")
                            .setLeftStr("取消")
            );
            infoWindow.setCallback(code -> {
                if (code == CommonInfoWindow.RIGHT_BTN) {
                    goDownloadMap();
                }

            });
            infoWindow.showPopupWindow();
//            openWebNavi(slat, slon, sname, dlat, dlon, dname);
        }

    }

    public static void openGaoDeNavi (double slat, double slon, String sname, double dlat, double dlon, String dname) {
        String uriString = null;
        StringBuilder builder = new StringBuilder("amapuri://route/plan?sourceApplication=maxuslife");
        final double[] start = bdToGaoDe(slat, slon);
        final double[] end = bdToGaoDe(dlat, dlon);
        if (slat != 0) {
            builder.append("&sname=").append(sname)
                    .append("&slat=").append(start[0])
                    .append("&slon=").append(start[1]);
        }
        builder.append("&dlat=").append(end[0])
                .append("&dlon=").append(end[1])
                .append("&dname=").append(dname)
                .append("&dev=0")
                .append("&t=0");
        uriString = builder.toString();
        final boolean isSuccess = goMap(Uri.parse(uriString), "com.autonavi.minimap");
        if (!isSuccess) {
//            openTxDeNavi(slat, slon, sname, dlat, dlon, dname);
            final CommonInfoWindow infoWindow = new CommonInfoWindow(MainApplication.getApplication(),
                    CommonInfoWindow.createBuilder()
                            .setInfo("当前未安装高德地图，是否去安装？")
                            .setRightStr("确定")
                            .setLeftStr("取消")
            );
            infoWindow.showPopupWindow();
            infoWindow.setCallback(code -> {
                if (code == CommonInfoWindow.RIGHT_BTN) {
                    goDownloadMap();
                }

            });
        }

    }

    private static void openTxDeNavi (double slat, double slon, String sname, double dlat, double dlon, String dname) {
        String uriString = null;
        StringBuilder builder = new StringBuilder("qqmap://map/routeplan?type=drive&policy=0&referer=zhongshuo");
        final double[] start = map_bd2tx(slat, slon);
        final double[] end = map_bd2tx(dlat, dlon);
        if (slat != 0) {
            builder.append("&from=").append(sname)
                    .append("&fromcoord=").append(start[0])
                    .append(",")
                    .append(start[1]);
        }
        builder.append("&to=").append(dname)
                .append("&tocoord=").append(end[0])
                .append(",")
                .append(end[1]);
        uriString = builder.toString();
        final boolean isSuccess = goMap(Uri.parse(uriString), "com.tencent.map");
        if (!isSuccess) {
            openWebNavi(slat, slon, sname, dlat, dlon, dname);
        }
    }

    /**
     * 打开Web地图导航
     */
    private static void openWebNavi (double slat, double slon, String sname, double dlat, double dlon, String dname) {

        final Intent intent = new Intent(MainApplication.getApplication(), CommonWebActivityControl.class);
        Bundle bundle = new Bundle();
        bundle.putString(BundleKey.URL,
                " http://uri.amap.com/navigation?from=" + slon + "," + slat + "&to=" + dlon + "," + dlat + "&mode=car&src=nyx_super"
        );
        intent.putExtras(bundle);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        MainApplication.getInstance().startActivity(intent);
    }

    /**
     * 百度转高德
     *
     * @param bd_lat
     * @param bd_lon
     * @return
     */
    public static double[] bdToGaoDe (double bd_lat, double bd_lon) {
        return MapManager.bd2GaoDe(bd_lat, bd_lon);
    }

    /**
     * 坐标转换，百度地图坐标转换成腾讯地图坐标
     *
     * @param lat 百度坐标纬度
     * @param lon 百度坐标经度
     * @return 返回结果：纬度,经度
     */
    public static double[] map_bd2tx (double lat, double lon) {
        double tx_lat;
        double tx_lon;
        double x_pi = 3.14159265358979324;
        double x = lon - 0.0065, y = lat - 0.006;
        double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
        double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
        tx_lon = z * Math.cos(theta);
        tx_lat = z * Math.sin(theta);
        return new double[]{tx_lat, tx_lon};
    }

    /**
     * @param uri
     * @return 是否跳转成功
     */
    private static boolean goMap (Uri uri, String packageName) {
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (!StringUtils.isEmpty(packageName)) {
            intent.setPackage(packageName);
        }
        boolean isSuccess = false;
        try {
            MainApplication.getInstance().startActivity(intent);
            isSuccess = true;
        } catch (ActivityNotFoundException e) {
            LogS.w("ActivityNotFoundException", "uri" + uri.toString());
        }
        return isSuccess;
    }

    public static void goDownloadMap () {
        try {
            Uri uri = Uri.parse("market://details?id=" + "com.autonavi.minimap");
            Intent intent2 = new Intent(Intent.ACTION_VIEW, uri);
            intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            MainApplication.getInstance().startActivity(intent2);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

    /**
     * 米转千米
     *
     * @param m
     * @return
     */
    public static double mToKm (double m) {
        return NumberUtils.bigDecimalOf(m).divide(new BigDecimal(1000)).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    /**
     * 获取距离，大于1Km时，不显示小数
     * 小于1km时展示单位为m
     *
     * @param m
     * @return
     */
    public static String getDistance (double m) {
        if (m < 1000) {
            return m + "m";
        }
        return mToKm(m) + "km";
    }


    public static boolean isGpsOpen (Activity activity) {
        LocationManager lm = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
        boolean ok = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (!ok) {
            final CommonInfoWindow infoWindow = new CommonInfoWindow(activity,
                    CommonInfoWindow.createBuilder()
                            .setInfo("请开启GPS定位服务，\n否则无法正常使用本应用!")
                            .setRightStr("去开启")
                            .setLeftStr("退出")
            );
            infoWindow.showPopupWindow();
            infoWindow.setCallback(code -> {
                if (code == CommonInfoWindow.RIGHT_BTN) {
                    Intent intent = new Intent();
                    intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    activity.startActivityForResult(intent, PRIVATE_CODE);
                } else if(code == CommonInfoWindow.LEFT_BTN){
                    activity.finish();
                }
            });
        }
        return ok;
    }

}
